// UdpReceiver.cpp
#include "udp_receive.h"
#include <QHostAddress>
#include <QDebug>
#include <QQueue>

QQueue<QByteArray>global_queue;

UdpReceiver::UdpReceiver(Ui::MainWindow *_ui, QObject *parent) : QObject(parent), udpSocket(new QUdpSocket(this)) {
    ui = _ui;

    // 初始化 udpSocket
}

UdpReceiver::~UdpReceiver() {
    delete udpSocket;
}

void UdpReceiver::startReceiver(quint16 port) {
    if (!udpSocket->bind(QHostAddress::Any, port)) {
        qDebug() << "绑定端口失败";
        ui->textEditDebug->append("绑定端口失败");
        return;
    }
    connect(udpSocket, &QUdpSocket::readyRead, this, &UdpReceiver::readPendingDatagrams);
    qDebug() << "UDP 接收器已启动，监听端口：" << port;
    ui->textEditDebug->append( "UDP 接收器已启动，监听端口：" +QString::number(port));

}

void UdpReceiver::stopReceiver() {
    udpSocket->abort();
    qDebug() << "UDP 接收器已停止";
    ui->textEditDebug->append( "UDP 接收器已停止");
}

void UdpReceiver::readPendingDatagrams() {
    while (udpSocket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(udpSocket->pendingDatagramSize());
        QHostAddress senderAddress;
        quint16 senderPort;
        // 读取数据存放到datagram中
        udpSocket->readDatagram(datagram.data(), datagram.size(), &senderAddress, &senderPort);
        dataProcess(datagram);
        qDebug() << "receive data ";
    }
}

void UdpReceiver::dataProcess(QByteArray& datagram){
    // datagram可以当做是一个数据报了，在本程序中，正确的一帧数据报应该是PACK_SIZE
    qDebug()<<"datagram size is:"<<datagram.size();


    memcpy(&P_head , datagram.data() , sizeof(PackageHeader));
    // 包头不对
    if(P_head.Header != 0x32)   return ;
    // 第一次接收数据
    if(cur_pic == -1 ){
        cur_pic = P_head.cur_pic;
    }
    // 下一包了
    if(cur_pic != P_head.cur_pic){
       cur_pic = P_head.cur_pic;

    }
    // 组装图像数组数据,如果不是最后一帧且长度不是PACK_SIZE，则reszize到PACK_SIZE
    if(!P_head.last && datagram.size() != PACK_SIZE){
        datagram.resize(PACK_SIZE);
    }
    img_array.append(datagram.mid(sizeof(PackageHeader)));


    // 图片的最后一包
    if(P_head.last){
        global_queue.enqueue(img_array);
        qDebug()<<"the size of encoder img is "<<img_array.size();
        ui->textEditDebug->append( "图片字节流大小为: "+QString::number(img_array.size()));
        img_array.clear();
    }

}























